// localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaW5mbyI6eyJpZCI6IjEiLCJsb2dpbl9uYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6Ijk2ZTc5MjE4OTY1ZWI3MmM5MmE1NDlkZDVhMzMwMTEyIiwibmFtZSI6IlRoaW5rSlPkuIDlk6UiLCJlbWFpbCI6Imhld3UxMTIyQDE2My5jb20iLCJwaG9uZSI6IjE3MzQyMDY1OTA5IiwibG9naW5faXAiOiI6OjEiLCJsb2dpbl9kYXRlIjoiMjAxOC0wMS0wOCAxNjoyMjo1MSIsImNyZWF0ZV9kYXRlIjoiMjAxNy0xMi0xNCAxMTo1Mjo0NiIsInVwZGF0ZV9kYXRlIjoiMjAyMy0wNi0xNSAwNzo1ODo1OCIsImRlbF9mbGFnIjoiMCIsInJvbGVfaWQiOlsiMWM1NGUwMDNjMWZjNGRjZDliMDg3ZWY4ZDQ4YWJhYzMiXSwic3RhdHVzIjoxLCJkZWZhdWx0X2RhdGEiOiIxIiwicm9sZW5hbWUiOlsi6LaF57qn566h55CG5ZGYIl19LCJpYXQiOjE2ODY5NzIyNzl9.xl_rD0eBqXMPaEZjjmhS51vkkmm_KwROJvYYNf1GUDQ')
// 封装发送筛选请求的对象
let query = {
  advposdesc: '',
  advposname: '',
  page: 1,
  limit: 10
}

//获取数据
const list = document.querySelector('#list')
reader()
async function reader() {
  const { data: { data: { data, count } } } = await axios.get('/ydd_advpos/list', { params: query })
  // console.log(data);
  renderPage(count)
  list.innerHTML = data.map(({ id, advposname, advposdesc, advpossize, default_data }, index) => `<tr>
    <td>${index + 1}</td>
    <td name="one">${advposname}</td>
    <td name="two">${advposdesc}</td>
    <td name="three">${default_data}</td>
    <td name="four">${advpossize}</td>
    <td>
      <button type="button" class="layui-btn layui-btn-xs btn_edit iconfont icon-xiugai edit" data-id=${id}></button>
      <button type="button" class="layui-btn layui-btn-danger layui-btn-xs btn_delete iconfont icon-shanchu del" data-id=${id}></button>
    </td>
  </tr>`).join('')
}

// 点击刷新，重新获取数据
document.querySelector('#flushed').addEventListener('click', function () {
  document.querySelector('.flushed').click()
  layer.msg('刷新成功');
})


// 修改模态框
const reviseForm = `   
<form id="reviseForm" class="layui-form">
<!-- id  隐藏 -->
<div class="layui-form-item layui-hide">
  <label class="layui-form-label">id</label>
  <div class="layui-input-block">
    <input type="text" name="id" required lay-verify="required" placeholder="请输入广告位名称" autocomplete="off"
      class="layui-input">
  </div>
</div>
<!-- 第一行 分类名称 -->
<div class="layui-form-item">
  <label class="layui-form-label">*广告位名称</label>
  <div class="layui-input-block">
    <input type="text" name="advposname" required lay-verify="required" placeholder="请输入广告位名称" autocomplete="off"
      class="layui-input">
  </div>
</div>
<!-- 第二行 分类别名  -->
<div class="layui-form-item">
  <label class="layui-form-label">*广告位描述</label>
  <div class="layui-input-block">
    <textarea name="advposdesc" placeholder="请输入广告位描述" lay-verify="required" class="layui-textarea"></textarea>
  </div>
</div>
<!-- 第三行 分类别名  -->
<div class="layui-form-item">
  <label class="layui-form-label">*广告位尺寸</label>
  <div class="layui-input-block">
    <input type="text" name="advpossize" required lay-verify="required" placeholder="请输入广告位尺寸" autocomplete="off"
      class="layui-input">
  </div>
</div>
<!-- 第三行 按钮 -->
<div class="layui-form-item">
  <div class="layui-input-block">
  <i class="layui-btn layui-btn-primary" id="cancel1">取消</i>
    <button class="layui-btn" lay-submit lay-filter="formDemo" id='enter'>确认</button>
  </div>
</div>
</form>
`
// 删除
let indexReviseForm      //修改文章的弹出层的index
list.addEventListener('click', async function (e) {
  if (e.target.className === 'layui-btn layui-btn-danger layui-btn-xs btn_delete iconfont icon-shanchu del') {
    // console.log(55);
    const { id } = e.target.dataset
    // console.log(id);
    //!优化删除当页最后一个内容的bug
    if ($('.del').length === 1) query.page = query.page - 1
    if (query.page <= 1) query.page = 1
    const { data: { errmsg, errno } } = await axios.get(`/ydd_advpos/del?id=${id}`)
    // console.log(data);
    if (errno === 1000) return layer.msg(errmsg);
    layer.msg('删除成功');
    reader()

  }

  //点击修改弹框
  if (e.target.className === 'layui-btn layui-btn-xs btn_edit iconfont icon-xiugai edit') {
    // console.log(55);
    const { id } = e.target.dataset
    // console.log(id);
    indexReviseForm = layer.open({
      type: 1,
      title: ['客官要修改什么呢', 'font-size:22px;'],
      shade: 0.6, // 遮罩透明度
      content: reviseForm,
      area: ['800px', '400px']
    });
    //拿到的index是一个重要的凭据，它是诸如layer.close(index)等方法的必传参数。
    const { data: { data } } = await axios.get(`/ydd_advpos/rowInfo?id=${id}`)
    // console.log(data);
    const names = document.querySelectorAll('#reviseForm [name]')
    // console.log(names);
    names.forEach(ele => {
      ele.value = data[ele.name]
    })
    // reader()
  }
})

$('body').on('submit', '#reviseForm', async function (e) {
  //点击修改发送请求
  e.preventDefault()
  // console.log(22);
  const data = $('#reviseForm').serialize()
  // console.log(data);
  const res = await axios.post('/ydd_advpos/update', data)
  // console.log(res);
  reader()
  layer.close(indexReviseForm)
  layer.msg('修改成功');
})


// 添加模态框
const addForm = `
<form id="addForm" class="layui-form">
<!-- 第一行 分类名称 -->
<div class="layui-form-item">
  <label class="layui-form-label">*广告位名称</label>
  <div class="layui-input-block">
    <input type="text" name="advposname" required lay-verify="required" placeholder="请输入广告位名称" autocomplete="off"
      class="layui-input">
  </div>
</div>
<!-- 第二行 分类别名  -->
<div class="layui-form-item">
  <label class="layui-form-label">*广告位描述</label>
  <div class="layui-input-block">
  <textarea name="advposdesc" placeholder="请输入广告位描述" lay-verify="required" class="layui-textarea"></textarea>
  </div>
</div>
<!-- 第三行 分类别名  -->
<div class="layui-form-item">
  <label class="layui-form-label">*广告位尺寸</label>
  <div class="layui-input-block">
    <input type="text" name="advpossize" required lay-verify="required" placeholder="请输入广告位尺寸" autocomplete="off"
      class="layui-input">
  </div>
</div>
<!-- 第三行 按钮 -->
<div class="layui-form-item">
  <div class="layui-input-block">
  <i class="layui-btn layui-btn-primary" id="cancel2">取消</i>
    <button class="layui-btn" lay-submit lay-filter="formDemo" id='enter'>确认</button>
  </div>
</div>
</form>
`



//点击添加弹框
let indexAddForm          //添加文章的弹出层的index
document.querySelector('#addTo').addEventListener('click', function () {
  indexAddForm = layer.open({
    type: 1,
    title: ['客官要添加什么呢', 'font-size:22px;'],
    shade: 0.6, // 遮罩透明度
    content: addForm,
    area: ['800px', '400px']
  });
  //拿到的index是一个重要的凭据，它是诸如layer.close(index)等方法的必传参数。
})



// 添加
// const formObj = document.querySelector('#addForm')
document.body.addEventListener('submit', async function (e) {
  // 点击添加发送请求
  if (e.target.id === 'addForm') {
    e.preventDefault()
    // console.log(22);
    const data = $('#addForm').serialize()
    // console.log(data);
    const res = await axios.post('/ydd_advpos/add', data)
    // console.log(res);
    reader()
    layer.close(indexAddForm)
    layer.msg('添加成功');
  }


})




// 取消
document.body.addEventListener('click', function (e) {
  if (e.target.id === 'cancel1') {
    // console.log(55);
    layer.close(indexReviseForm)
    // formObj.reset()
  }
  if (e.target.id === 'cancel2') {
    // console.log(55);
    layer.close(indexAddForm)
    // formObj.reset()
  }

})


// 隐藏
let flag = true
$('#hide').click(() => {
  flag ? $('#search').slideUp() : $('#search').slideDown()
  $('#hide')[0].className = flag ? "iconfont icon-xiajiantou" : "iconfont icon-shangjiantou"
  flag = !flag
})

// 分页
function renderPage(total) {
  layui.use('laypage', function () {
    let laypage = layui.laypage;

    //执行一个laypage实例
    laypage.render({
      elem: 'page-box' //注意，这里的 test1 是 ID，不用加 # 号
      , count: total //数据总数，从服务端得到
      , limit: query.limit
      , curr: query.page
      , limits: [2, 3, 5, 10, 20]
      , layout: ['count', 'limit', 'prev', 'page', 'next', 'skip']
      , jump: function (obj, first) {
        // jump的触发机制：
        // 1、分页渲染会触发回调函数
        // 2、当分页切换的时候也会触发
        //obj包含了当前分页的所有参数，比如：
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        query.page = obj.curr
        query.limit = obj.limit
        //首次不执行
        if (!first) {
          //do something
          reader()
        }
      }
    });
  });

}

// 搜索请求数据
document.querySelector('#search').addEventListener('submit', function (e) {
  e.preventDefault()
  const text = document.querySelector('#btn').value.trim()
  // console.log(text);
  query.advposname = text
  query.advposdesc = text
  reader()
  layer.msg('搜索成功');
})

//重置按钮
document.querySelector('#reset').addEventListener('click', function () {
  query = {
    advposdesc: '',
    advposname: '',
    page: 1,
    limit: 10
  }
  reader()
  layer.msg('重置成功');
})



// 点击显示隐藏菜单
let flag1 = true
$('#pullDown').on('click', function (e) {
  e.stopPropagation()
  flag1 ? $('#menu').show() : $('#menu').hide()
  flag1 = !flag1
})
$('#menu').on('click', function (e) {
  e.stopPropagation()
  $('#menu').show()
})
// 点击页面让菜单消失
$('body').on('click', function () {
  $('#menu').hide()
  flag1 = true
})

// 点击隐藏列
$('body').on('change', '.cked', function () {
  // console.log(this.checked);
  // console.log($('#test [name="one"]'));
  this.checked ? $(`#test [name=${this.id}]`).show() : $(`#test [name=${this.id}]`).hide()
})


